package com.aliengen.thingple.thingple.tag;

import com.aliengen.thingple.cmc168mwithservice.Common;
import com.aliengen.thingple.thingple.tag.exception.InvalidTagException;

import java.io.Serializable;

/**
 * This class is part of the Thingple mobile application for the CMC168 Handheld reader.
 *
 * Copyright AlienGen Limited 2016. All rights reserved.
 *
 * @author Timothé Mermet-Buffet <tim@aliengen.com>
 */
public class Tag implements Serializable {
    protected byte[] tag;

    protected int tagType;
    protected int operation_id;
    protected TruckTag truck;
    protected String tagId;
    protected byte[] epc;
    protected String userMemory;

    protected char b(int position) throws InvalidTagException
    {
        if(this.epc.length <= position) {
            throw new InvalidTagException("Tag too small! size=" + this.epc.length + ", position=" + position);
        }
        return (char)this.epc[position];
    }

    public Tag(byte[] tag) throws InvalidTagException
    {
        this.epc = tag;

        if(tag.length < 16)
        {
            throw new InvalidTagException("Tag memory size too short!");
        }

        if(b(0) != 0x55) {
            throw new InvalidTagException("Not BaoSteel tag! " + (int)b(0) + " size=" + tag.length);
        }

        this.tagType = (b(1) & 0x0F);

        this.tag = tag;
        this.tagId = "";
        this.userMemory = "";
    }

    public byte[] getEpc() {
        return this.epc;
    }

    public int getType() { return this.tagType; }

    public void setOperationId(int operation_id)
    {
        this.operation_id = operation_id;
    }

    public int getOperationId() { return this.operation_id; }

    public TruckTag getTruck()
    {
        return this.truck;
    }

    public void setTruck(TruckTag t)
    {
        this.truck = t;
    }

    @Override
    public String toString() {
        return Common.arrByte2String(this.tag, 0, this.tag.length);
    }
}
